package com.example.myfirstapplication

import android.content.Context
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.core.content.edit
import com.example.myfirstapplication.data.*
import com.example.myfirstapplication.utils.*
import com.example.myfirstapplication.utils.OkHttpUtils.Companion.mOkHttpUtils
import com.google.gson.Gson
import kotlinx.android.synthetic.main.activity_login.*
import okhttp3.Response
import okio.IOException
import java.lang.Exception
import java.text.SimpleDateFormat
import java.util.*

class LoginActivity : BaseActivity() {
    private var username: String = ""
    private var password: String = ""
    private lateinit var ipInfo: IP_Data
    private lateinit var cityInfo: Weather_Data

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)

        val intentObj = intent
        val myId = intentObj.extras?.getString("myId")
        Log.i(Tag,"通知传递过来的数据：$myId")

        //登录登录登录登录登录登录登录登录登录登录登录登录
        val passwordSPF = getSharedPreferences("password", Context.MODE_PRIVATE)
        val isRemember = passwordSPF.getBoolean("rememberPassword", false)
        val remberTime = passwordSPF.getString("rememberTime", "")
        val currentTime = getTimeFormat()
        rememberTime_layoutLogin.text = remberTime
        //Log.i(Tag, "rememberTime:" + remberTime)
        //Log.i(Tag, "currentTime:" + currentTime)
        if (getLoginDataFromFile(currentTime, remberTime!!)) {
            if (isRemember) {
                username = passwordSPF.getString("username", "").toString()
                password = passwordSPF.getString("password", "").toString()
                usernameET.setText(username)
                usernameET.setSelection(username.length)
                passwordET.setText(password)
                rememberPassCB.isChecked = true
            } else {
                Log.i(Tag, "未勾选记住密码")
            }
        }
        btnLogin_layoutLogin.setOnClickListener {
            username = usernameET.text.toString()
            password = passwordET.text.toString()
            //   var nowtime = Calendar.getInstance()
            if (username == "117060100133" && password == "666666") {
                if (rememberPassCB.isChecked) {
                    passwordSPF.edit {
                        putString("username", username)
                        putString("password", password)
                        putBoolean("rememberPassword", true)
                        putString("rememberTime", getTimeFormat())
                    }
                    goActivity(this,BroadcastActivity::class.java)
                    Log.i(Tag, "passwordSPF保存成功")
                } else {
                    passwordSPF.edit().clear().apply()
                    Toast.makeText(this, "清空成功", Toast.LENGTH_SHORT).show()
                }
                myToast(this, "登录成功")
            } else {
                myToast(this, "密码错误!")
            }
        }

        //地址地址地址地址地址地址地址地址地址地址地址地址地址地址
        val ipRemberTime = FileOP().readForLogin(this@LoginActivity, "ipFile.json")
        val ipCurrentTime = getTimeFormat()
        Log.i(Tag, "ipRememberTime:" + ipRemberTime)
        Log.i(Tag, "ipCurrentTime:" + ipCurrentTime)
        if (ipTimeCMP(ipCurrentTime, ipRemberTime!!)) {
            val json = FileOP().read(this@LoginActivity, "ipFile.json")
            if (json.isNotEmpty()) {
                textIP_layoutLogin.setText(json).toString()
                myToast(this, "ipData from file")
                Log.i(Tag, "文件读取ip")
            } else {
                Log.i(Tag, "联网读取ip")
            }
        } else {
            Log.i(Tag, "超出1小时")
        }
        btnGetIPData_layoutLogin.setOnClickListener {
            //初始化OkHttp环境
            OkHttpUtils(this)
            val url = "https://widget.cifuwu.com/ip"
            OkHttpUtils.mOkHttpUtils.get_Async(url, object : OkHttpUtils.OkHttpCallback {
                override fun onResponse(response: Response) {
                    if (response.isSuccessful) {
                        val json = response.body?.string()
                        ipInfo = Gson().fromJson(json!!, IP_Data::class.java)
                        Log.i(Tag, response.toString() + json)
                        var outInfo =
                            ipInfo.data.ref_2.country + ipInfo.data.ref_2.province + ipInfo.data.ref_2.city
                        TimeHours_layoutLogin.text = "刷新获取新IP数据"
                        textIP_layoutLogin.setText(outInfo)
                        outInfo += "\n" + getTimeFormat()
                        //存储数据
                        FileOP().save(this@LoginActivity, "ipFile.json", outInfo)
                        myToast(this@LoginActivity, "ipData from internet")
                    }
                }

                //object的成员函数
                override fun onError(e: IOException) {
                    Log.i(Tag, e.message.toString())
                }

            })
        }

        //天气天气天气天气天气天气天气天气天气天气天气天气
        val newTime = getTimeFormat()
        val oldTime = FileOP().readForLogin(this@LoginActivity, "weatherFile.json")
        if (ipTimeCMP(newTime, oldTime!!)) {
            val json = FileOP().read(this@LoginActivity, "weatherFile.json")
            if (json.isNotEmpty()) {
                txtCityWeather_weather.setText(json).toString()
                myToast(this, "weatherData from file")
            } else {
                Log.i(Tag, "internet city")
            }
        } else {
            Log.i(Tag, "over 6 hour")
        }

        btnCitySearch_weather.setOnClickListener {
            /*OkHttpUtils(this)
            val url = "https://widget.cifuwu.com/weather"
            OkHttpUtils.mOkHttpUtils.get_Async(url, object : OkHttpUtils.OkHttpCallback {
                override fun onResponse(response: Response) {
                    if (response.isSuccessful) {
                        val json = response.body?.string()
                        cityInfo = Gson().fromJson(json!!, Weather_Data::class.java)
                        Log.i(Tag, response.toString())
                        var outInfor =
                            cityInfo.data.pubtime + cityInfo.data.realtime.city_name + cityInfo.data.realtime.weather.temperature
//                        txtCityWeather_main.setText(outInfo)
//                        outInfo += "\n" + getTimeFormat()
                        txtCityWeather_weather.setText(outInfor)
                        outInfor += "\n" + getTimeFormat()
                        FileOP().save(this@LoginActivity, "weatherFile.json", outInfor)
                        myToast(this@LoginActivity, "weatherData from internet")
                    }
                }

                //object的成员函数
                override fun onError(e: IOException) {
                    Log.i(Tag, e.message.toString())
                }
            })*/
            getWeatherData()
        }
    }

    //时间获取处理
    private fun getTimeFormat(): String {
        var time = Calendar.getInstance()
        if (android.os.Build.VERSION.SDK_INT >= 23) {
            return SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date())
        } else {
            return time.get(Calendar.YEAR).toString() + "-" + time.get(Calendar.MONTH)
                .toString() + "-" + time.get(Calendar.DAY_OF_MONTH)
                .toString() + " " + time.get(
                Calendar.HOUR_OF_DAY
            ).toString() + ":" + time.get(Calendar.MINUTE)
                .toString() + ":" + time.get(Calendar.SECOND)
                .toString() + "." + time.get(Calendar.MILLISECOND).toString()
        }
    }

    //时间间隔判断
    private fun getLoginDataFromFile(strTime1: String, strTime2: String): Boolean {
        if (android.os.Build.VERSION.SDK_INT >= 23) {
            var df = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
            try {
                val now = df.parse(strTime1)
                val date = df.parse(strTime2)
                val lon = now.time - date.time       //获取时间差
                val day = lon / (24 * 60 * 60 * 1000)
                Log.i(Tag, "间隔天数：" + day)
                //   TimeDays_layoutLogin.text = day.toString() + "天"
                if (day < 30) {
                    return true
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        } else {
            return false
        }
        return false
    }

    //IP时间间隔判断
    private fun ipTimeCMP(strTime1: String, strTime2: String): Boolean {
        if (android.os.Build.VERSION.SDK_INT >= 23) {
            var df = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
            try {
                val now = df.parse(strTime1)
                val date = df.parse(strTime2)
                val timeLength = now.time - date.time       //获取时间差
                val hour = timeLength / (60 * 60 * 1000)
                Log.i(Tag, "相差小时：" + hour)
                //   rememberTimeHour_layoutLogin.text = date.toString()
                TimeHours_layoutLogin.text = hour.toString() + "小时"
                if (hour < 1) {
                    return true
                    //Log.i(Tag, "yeah！ip间隔1小时以内")
                } else {
                    //Log.i(Tag, "Oh no！ip间隔超过1小时")
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        } else {
            return false
        }
        return false
    }

    private fun getWeatherData() {
        //初始化Okhttp环境
        OkHttpUtils(this)
        val url = "https://widget.cifuwu.com/weather"
        mOkHttpUtils.get_Async(url, object : OkHttpUtils.OkHttpCallback {
            override fun onResponse(response: Response) {
                val test1 = response.toString()
                Log.i(Tag, "test1$test1")
                if (response.isSuccessful) {
                    val test2 = response.body?.string()
                    Log.i(Tag, "test2$test2")
                    val test3 = response.body.toString()
                    Log.i(Tag, "test3$test3")
                }
            }

            override fun onError(e: IOException) {
                Log.i(Tag, e.toString())
            }
        })
    }
}